import { Button, Form, Input, Radio, Select,} from "antd";
import {Link, useLocation, Outlet, useNavigate} from "react-router-dom";
// import "./Help.css";
import {useEffect, useState} from "react";
import axios from "axios";

const {Option} = Select;
// eslint-disable-next-line react-hooks/rules-of-hooks


//登陆组件
export default function Login(){
    const [user, setUser] = useState(''); // 账号
    const [password, setPassword] = useState('');   // 密码
    const [form] = Form.useForm();
    const navigate = useNavigate();  // 只能在组件中使用

    const formItemLayout = {
        labelCol: {
            span: 4,
        },
        wrapperCol: {
            span: 14,
        },
    };
    const buttonItemLayout = {
        wrapperCol: {
            span: 14,
            offset: 4,
        },
    };


    function handleChangeUser(e){
        setUser(e.target.value)
    }

    function handleChangePassword(e) {
        setPassword(e.target.value);
    }


    function onFinish() {
        let data = {
            user: user,
            password: password,
        }
        axios.post('/api/login', data)
            .then( res => {
                console.log(res);
                if( res.data.status === 200 ){
                    localStorage.setItem("userData", JSON.stringify(data));  // 登陆成功后，设置到本地storage中去，用于后续登陆
                    console.log("登陆成功:", localStorage.getItem("userData"));
                    alert("登陆成功。");
                    navigate('/home/user')
                } else if( res.data.status === 404) {
                    alert("登陆失败，账号不存在");
                } else {
                    alert("登陆失败，密码错误");
                }
            })
    }

    return(
        <Form
            {...formItemLayout}
            layout={'horizontal'}
            form={form}
            initialValues={{
                layout: 'horizontal',
            }}
            onFinish={onFinish}
        >
            <Form.Item label="账号">
                <Input onChange={handleChangeUser} required={true}/>
            </Form.Item>
            <Form.Item
                name="password"
                label="密码"
            >
                <Input.Password onChange={handleChangePassword}/>
            </Form.Item>

            <Form.Item {...buttonItemLayout}>
                <Button type="primary" htmlType="submit">登 陆</Button>
            </Form.Item>
        </Form>
    )
}